<?php

namespace app\api\controller;

use app\api\controller\Common;
use app\api\model\Goods\Speci\Category as Model;
use think\App;
use think\Request;

/** 
 * Class Category
 * @package app\api\controller\Goods
 */
class Category extends Common
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->model = new Model();
    }

    /**
     * @var Model
     */
    protected $model;

    protected $field = ['name', 'sort', 'status', 'pid', 'des'];
    /**
     * @param Request $request
     * @param Model $model
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function list(Request $request)
    {
        $where = [];
        $request->has('name') ? $where[] = ['name', 'LIKE', '%' . $request->param('name') . '%']
            : $request->has('id') ? $where[] = ['pid', '=', $request->param('id')]
            : $where = [];
//        if ($request->has('name')) {
//            $where[] = ['name', 'LIKE', '%' . $request->param('name') . '%'];
//        }
//        if ($request->has('id')) {
//            $where[] = ['pid', '=', $request->param('id')];
//        }
        return $this->returnJson(
            200,
            'ok',
            $this->model->index($where, $request->param('page', 1), $request->param('size', 10))
        );
    }

    public function getAllCategory(Request $request)
    {
       return $this->returnJson(200,'ok',$this->model->getAllCategory());
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     */
    public function add(Request $request)
    {
        $data = $request->only($this->field);
        return $this->returnJson(200, 'ok', $this->model->add($data));
    }

    /**
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info($id)
    {
        return $this->returnJson(200, 'ok', $this->model->info($id));
    }

    /**
     * @param $id
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function edit($id, Request $request)
    {
        $data = $request->only($this->field);
        return $this->returnJson(200, 'ok', $this->model->edit($id, $data));
    }

    /**
     * @param int $id 属性id
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del($id)
    {
        return $this->model->del($id) ? $this->returnJson(200, 'ok') : $this->returnJson(500, '属性已绑定商品,无法删除');
    }
}
